package com.tang.util;

import com.alibaba.fastjson.JSON;
import com.tang.domain.ServerMsgProtocol;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 消息工具类
 *
 * @author fulin.tang
 * @version V3.0
 * @since 2022/5/18 15:19
 */
public class MsgUtil {

    private static MsgUtil instance;

    public static MsgUtil getInstance() {
        if (null != instance) return instance;
        Lock lock = new ReentrantLock();
        lock.lock();
        try {
            if (null == instance) {
                instance = new MsgUtil();
            }
        } finally {
            lock.unlock();
        }
        return instance;
    }

    private MsgUtil() {
    }

    public TextWebSocketFrame buildMsgAll(String channelId, String msgInfo) {
        // 模拟头像
        int i = Math.abs(channelId.hashCode()) % 10;
        ServerMsgProtocol msg = new ServerMsgProtocol();
        msg.setType(2);
        msg.setChannelId(channelId);
        msg.setUserHeadImg("head" + i + ".jpg");
        msg.setMsgInfo(msgInfo);
        return new TextWebSocketFrame(JSON.toJSONString(msg));
    }

    public TextWebSocketFrame buildMsgOwner(String channelId) {
        ServerMsgProtocol msg = new ServerMsgProtocol();
        msg.setType(1);
        msg.setChannelId(channelId);
        return new TextWebSocketFrame(JSON.toJSONString(msg));
    }

}
